/*
 * ProductosInventario.java
 *
 * Created on 7 de mayo de 2008, 02:46 PM
 */

package administrador;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;
import javax.swing.table.*;
import javax.swing.*;
import java.awt.*;
import java.sql.*;


/**
 *
 * @author  Usuario
 */
public class ProductosInventario extends javax.swing.JFrame {
 Usuario user;
 int bodega;
 Conexion conexion;
 JTable tabla;
 JScrollPane js;
 String cod_inv;
 BuscadorProducto bp;
 
    /** Creates new form ProductosInventario */
    public ProductosInventario(String cod_inv,Conexion cEnt,int BEnt,Usuario user) {
        setVisible(true);
        setSize(900,550);
        
        bodega=BEnt;
       //System.out.println("La bodega en uso es:"+bodega);
        conexion=cEnt;
        initComponents();
        this.user=user;
        this.cod_inv=cod_inv;
        bp= new BuscadorProducto(conexion,this,bodega);
        refrescar();
        
    }
    
    
     public void refrescar(){
    
        ResultSet respuesta=null;
        respuesta=conexion.consultarBase("select * from productoinv where cod_inv="+cod_inv+";");
          
        //Obtengo Filas-Arreglo de Titulos de Columnas
        int filas=conexion.obtenerFilas(respuesta);
        String[] titulosCol=conexion.obtenerColumnas(respuesta);
        
        //Creo la tabla:
        
        CrearTabla(filas,titulosCol);
        llenaTabla(respuesta,titulosCol.length,filas);
       //
        System.gc();
       
    }
    
    public void llenaTabla(ResultSet r,int columnas,int filas){
        try{
            r.beforeFirst();
            
            int j=0;
            while(r.next()) {
                
                
                for(int i=0;i<columnas;i++) {
                    
                    Object toma=r.getObject(i+1);
                    
                    //System.out.println("toma valor:"+toma+" * fila:"+j+" * column:"+i);
                    try{
                        tabla.setValueAt(toma,j,i);
                    }catch(java.lang.ArrayStoreException e){
                        tabla.setValueAt("null",j,i);
                    }
                }
                
            j++;    
            }
        }catch(SQLException sqle){
           //System.out.println("Error al mostrar los datos");
            System.err.println(sqle);
        }
        
    }
    
public void CrearTabla(int filas,String[] titulos){
        
        int columnas=titulos.length;
        String[][] tabla0=new String[filas][columnas];
       
        tabla= new JTable(tabla0,titulos);
        
        //Aqui le especifico para que la tabla acepte valores doubles e int:
        //--------------------------------------------------------------------
        final boolean[] canEdit = new boolean [columnas];
        for(int p=0;p<columnas;p++){
        canEdit[p]=false;
        }
        tabla.setModel(new javax.swing.table.DefaultTableModel(
            tabla0,titulos  
        ) {
           // boolean[] canEdit = new boolean [] { false, false, false, false};

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        //---------------------------------------------------------------------
         //Le doy el evento del LCick del Mouse:
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        //remuevo el JScroll para que no se monte cuando cree el nuevo:
        //*************************************************************
        try{
        jPanel1.remove(js);
        }catch(java.lang.NullPointerException e){}
        //*************************************************************
        
        //Pongo en la tabla:
            js = new JScrollPane(tabla);
                        
            js.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(198, 196, 196)));
            js.setBounds(22, 100, 680, 400);
            js.setVisible(true);
            jPanel1.add(js);
            js.updateUI();
    }
 

 private void tablaMouseClicked(java.awt.event.MouseEvent evt) {
    // Evento del click del mouse sobre la tabla:
       modificarP();
 }
  
 public void modificarP(){
         int fila=tabla.getSelectedRow();
        //System.out.println("#########################3333");
        //System.out.println("Click en la Fila :"+fila);
         String codigop=String.valueOf(tabla.getValueAt(fila,1));
        //System.out.println(tabla.getValueAt(fila,0));
        //System.out.println("Codigo Producto:"+codigop);
         
         String codigoi=cod_inv;
         VentModPInv vmpi=new VentModPInv(this,codigoi,codigop,conexion,bodega,user);
 }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        txt_buscar = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Productos del Inventario"));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setText("Productos del Inventario");

        jButton1.setText("Buscar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        txt_buscar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txt_buscarKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txt_buscarKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txt_buscarKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(txt_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(176, 176, 176))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txt_buscar, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addContainerGap(488, Short.MAX_VALUE))
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txt_buscarKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_buscarKeyReleased
// TODO add your handling code here:
        int t=evt.getKeyChar();
        if(t==10){
           System.gc();
             buscarP();
        }

    }//GEN-LAST:event_txt_buscarKeyReleased
public void buscarP(){
        refrescar();
        
        String buscar=txt_buscar.getText();
        
        int seleccion=0;
        
        for (int i = 0; i < tabla.getRowCount(); i++) {
            String compara=String.valueOf(tabla.getValueAt(i,1));
            compara=compara.replaceAll(" ","");
            
           //System.out.println("Compara :"+buscar+" : "+compara+" fila# "+seleccion);
            if(buscar.equalsIgnoreCase(compara)){
                seleccion=i;
               //System.out.println("Encontro:"+seleccion);
                break;
            }
            
        }
        tabla.addRowSelectionInterval(seleccion,seleccion);
        // scroll to the editing field
        tabla.scrollRectToVisible(tabla.getCellRect(seleccion, 1, true));


}
    private void txt_buscarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_buscarKeyPressed
// TODO add your handling code here:
       
    }//GEN-LAST:event_txt_buscarKeyPressed

    private void txt_buscarKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_buscarKeyTyped
// TODO add your handling code here:
    }//GEN-LAST:event_txt_buscarKeyTyped

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    abrirBuscador();
    }//GEN-LAST:event_jButton1ActionPerformed

    public void abrirBuscador(){
    bp.reaparecer();
    }
    /**
     * @param args the command line arguments
     
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ProductosInventario().setVisible(true);
            }
        });
    }
    */
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    public javax.swing.JTextField txt_buscar;
    // End of variables declaration//GEN-END:variables
    
}
